package com.example.jpetstoreback.controller;

import com.example.jpetstoreback.common.CommonResponse;
import com.example.jpetstoreback.entity.Employee;
import com.example.jpetstoreback.persistence.EmployeeMapper;
import com.example.jpetstoreback.service.AccountService;
import com.example.jpetstoreback.utils.RedisUtils;
import com.example.jpetstoreback.utils.SMSUtils;
import com.example.jpetstoreback.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/accounts/")
@Slf4j
public class AccountController {

    @Autowired
    private AccountService accountService;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 获取验证码
     * @param employee
     * @return
     */
    @PostMapping("validateCode")
    @ResponseBody
    public CommonResponse<String> sendMsg(@RequestBody Employee employee){
        //获取手机号
        String phone = employee.getPhone();
        log.info("phone={}", phone);

        if(StringUtils.isNotEmpty(phone)){
            //生成随机的四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            //调用阿里云提供的短信服务API完成发送信息
            SMSUtils.sendMessage("JPetStore", "SMS_275010091", phone, code);

            //需要将生成的验证码保存到redis，时长五分钟
            redisUtils.set(phone, code, 5);

            return CommonResponse.createForSuccessMessage("手机短信验证码发送成功！");
        }

        return CommonResponse.createForError("短信发送失败！");
    }

    /**
     * 用户登录
     * @param map
     * @return
     */
    @PostMapping("login")
    @ResponseBody
    public CommonResponse<Employee> login(@RequestBody Map map){
        String code = (String) map.get("code");
        String phone = (String) map.get("phone");
        String employeeId = (String) map.get("employeeId");
        String password = (String) map.get("password");

        //用验证码登录
        if(StringUtils.isNotEmpty(code)){
            //从session中获取保存的验证码
            String storedCode = redisUtils.get(phone);
            //进行验证码的比对
            if(storedCode != null && storedCode.equals(code)){
                redisUtils.delete(phone);
                return accountService.getAccountByPhoneAndCode(phone);
            }
        }else {
            //2.用账号密码登录
            return accountService.getAccountByEmpIdAndPwd(employeeId, password);
        }
        return CommonResponse.createForError("验证码错误！");
    }
}
